/* $RCSFile: CRMImage.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageManager/PageModules/CRMImage/CRMImage.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:56:46  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 7 2010/08/09 09:44:01  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Security;

using AddonNice.CRMImage;
using AddonNice.Settings.CRMImage;
using AddonNice.CRMImage.UI.WebControls;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using AddonNice.CRMWrapper.CRMImage;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;


namespace AddonNice.PageModules.CRMImage
{
    /// <summary>
    /// Initializer class for CRMImage 
    /// </summary>
    public class CRMImageSI : PortalCRMModuleControlSI
    {
        public CRMImageSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                       =   pm.ExtendedResourcesGroup;
            
			SettingItemSpecial ImageLibId	    =   new SettingItemSpecial(ImStr.ImageLibId,new IntegerDataType());
			ImageLibId.Value				    =   "0";
			ImageLibId.Order				    =   2;
            ImageLibId.ExtendedGroupName        =   extgrp;
            ImageLibId.ResourceFile             =   ImStr.ResourceFile;
            ImageLibId.ResourceItem             =   ImStr.ResourceItem;
            ImageLibId.EnglishName			    =   "Image library Id";
            ImageLibId.Description			    =   "Integer which defines the image library associated with this module";
			bSettings.AddSetting(ImageLibId);

            // Should we use a special folder for images files or default portal one
			SettingItemSpecial CustomAlbumPath	=   new SettingItemSpecial(ImStr.CustomAlbumPath,new BooleanDataType());
			CustomAlbumPath.Value				=   StStr.strFalse;
			CustomAlbumPath.Order				=   5;
            CustomAlbumPath.ExtendedGroupName   =   extgrp;
            CustomAlbumPath.ResourceFile        =   ImStr.ResourceFile;
            CustomAlbumPath.ResourceItem        =   ImStr.ResourceItem;
            CustomAlbumPath.EnglishName			=   "Use a custom path for images";
            CustomAlbumPath.Description			=   "Check to use a different folder from the portal global folder";
			bSettings.AddSetting(CustomAlbumPath);

            // Images files folder path Special Setting
			SettingItemSpecial AlbumPath		=   new SettingItemSpecial(ImStr.AlbumPath,new PortalUrlDataType());
			AlbumPath.Required					=   true;
			AlbumPath.Value						=   "Album";
			AlbumPath.Order						=   10;
            AlbumPath.ExtendedGroupName         =   extgrp;
            AlbumPath.ResourceFile              =   ImStr.ResourceFile;
            AlbumPath.ResourceItem              =   ImStr.ResourceItem;
            AlbumPath.EnglishName				=   "Images Folder";
            AlbumPath.Description				=   "Folder where images will be stored after download";
			bSettings.AddSetting(AlbumPath);

			// Thumbnail Resize Options
			ArrayList thumbnailResizeOptions	= new ArrayList();
			thumbnailResizeOptions.Add(new SettingOption((int)PicResizeOption.FixedWidthHeight, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURE_FIXED_WIDTH_AND_HEIGHT", "Fixed width and height")));
			thumbnailResizeOptions.Add(new SettingOption((int)PicResizeOption.MaintainAspectWidth, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURE_MAINTAIN_ASPECT_FIXED_WIDTH", "Maintain aspect fixed width")));
			thumbnailResizeOptions.Add(new SettingOption((int)PicResizeOption.MaintainAspectHeight, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURE_MAINTAIN_ASPECT_FIXED_HEIGHT", "Maintain aspect fixed height")));

			// Thumbnail Resize Settings
			SettingItemSpecial ThumbnailResize	=   new SettingItemSpecial(ImStr.ThumbnailResize,new CustomListDataType(thumbnailResizeOptions, "Name", "Val"));
			ThumbnailResize.Required			=   true;
			ThumbnailResize.Value				=   ((int)PicResizeOption.FixedWidthHeight).ToString();
			ThumbnailResize.Order				=   20;
            ThumbnailResize.ExtendedGroupName   =   extgrp;
            ThumbnailResize.ResourceFile        =   ImStr.ResourceFile;
            ThumbnailResize.ResourceItem        =   ImStr.ResourceItem;
            ThumbnailResize.EnglishName			=   "Thumbnail resize";
            ThumbnailResize.Description			=   "Resize mode from downloaded image to full size image";
			bSettings.AddSetting(ThumbnailResize);

			// Thumbnail Width Setting
			SettingItemSpecial ThumbnailWidth	=   new SettingItemSpecial(ImStr.ThumbnailWidth,new UnitDataType());
			ThumbnailWidth.Required				=   true;
			ThumbnailWidth.Value				=   "200";
			ThumbnailWidth.Order				=   30;
			ThumbnailWidth.ExtendedGroupName    =   extgrp;
            ThumbnailWidth.ResourceFile         =   ImStr.ResourceFile;
            ThumbnailWidth.ResourceItem         =   ImStr.ResourceItem;
            //ThumbnailWidth.MinValue				= 2;
			//ThumbnailWidth.MaxValue				= 9999;
            ThumbnailWidth.EnglishName			=   "Thumbnail width";
            ThumbnailWidth.Description			=   "Width for thumbnail images";
			bSettings.AddSetting(ThumbnailWidth);

			// Thumbnail Height Setting
			SettingItemSpecial ThumbnailHeight =    new SettingItemSpecial(ImStr.ThumbnailHeight,new UnitDataType());
			ThumbnailHeight.Required			=   true;
			ThumbnailHeight.Value				=   "200";
			ThumbnailHeight.Order				=   40;
			ThumbnailHeight.ExtendedGroupName   =   extgrp;
            ThumbnailHeight.ResourceFile        =   ImStr.ResourceFile;
            ThumbnailHeight.ResourceItem        =   ImStr.ResourceItem;
            //ThumbnailHeight.MinValue			=   2;
			//ThumbnailHeight.MaxValue			=   9999;
            ThumbnailHeight.EnglishName			=   "Thumbnail Height";
            ThumbnailHeight.Description			=   "Height for thumbnail images";
			bSettings.AddSetting(ThumbnailHeight);

			// Original Resize Options
			ArrayList originalResizeOptions = new ArrayList();
			originalResizeOptions.Add(new SettingOption((int)PicResizeOption.NoResize, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURE_DONT_RESIZE", "Don't Resize")));
			originalResizeOptions.Add(new SettingOption((int)PicResizeOption.FixedWidthHeight, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURE_FIXED_WIDTH_AND_HEIGHT", "Fixed width and height")));
			originalResizeOptions.Add(new SettingOption((int)PicResizeOption.MaintainAspectWidth, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURE_MAINTAIN_ASPECT_FIXED_WIDTH", "Maintain aspect fixed width")));
			originalResizeOptions.Add(new SettingOption((int)PicResizeOption.MaintainAspectHeight, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURE_MAINTAIN_ASPECT_FIXED_HEIGHT", "Maintain aspect fixed height")));

			// Original Resize Settings
			SettingItemSpecial OriginalResize	=   new SettingItemSpecial(ImStr.OriginalResize,new CustomListDataType(originalResizeOptions, "Name", "Val"));
			OriginalResize.Required				=   true;
			OriginalResize.Value				=   ((int)PicResizeOption.MaintainAspectWidth).ToString();
			OriginalResize.Order				=   50;
            OriginalResize.ExtendedGroupName    =   extgrp;
            OriginalResize.ResourceFile         =   ImStr.ResourceFile;
            OriginalResize.ResourceItem         =   ImStr.ResourceItem;
            OriginalResize.EnglishName			=   "Full size Resize";
            OriginalResize.Description			=   "Resize mode from downloaded image to full size image";
			bSettings.AddSetting(OriginalResize);

			// Original Width Settings
			SettingItemSpecial OriginalWidth	=   new SettingItemSpecial(ImStr.OriginalWidth,new UnitDataType());
			OriginalWidth.Required				=   true;
			OriginalWidth.Value					=   "800";
			OriginalWidth.Order					=   60;
			OriginalWidth.ExtendedGroupName     =   extgrp;
            OriginalWidth.ResourceFile          =   ImStr.ResourceFile;
            OriginalWidth.ResourceItem          =   ImStr.ResourceItem;
            //OriginalWidth.MinValue				= 2;
			//OriginalWidth.MaxValue				= 9999;
            OriginalWidth.EnglishName			=   "Full size Width";
            OriginalWidth.Description			=   "Width for images displayed in full size";
			bSettings.AddSetting(OriginalWidth);

			// Original Height Settings
			SettingItemSpecial OriginalHeight	=   new SettingItemSpecial(ImStr.OriginalHeight,new UnitDataType());
			OriginalHeight.Required				=   true;
			OriginalHeight.Value				=   "600";
			OriginalHeight.Order				=   70;
			OriginalHeight.ExtendedGroupName    =   extgrp;
            OriginalHeight.ResourceFile         =   ImStr.ResourceFile;
            OriginalHeight.ResourceItem         =   ImStr.ResourceItem;
            //OriginalHeight.MinValue				= 2;
			//OriginalHeight.MaxValue				= 9999;
            OriginalHeight.EnglishName			=   "Full size Height";
            OriginalHeight.Description			=   "Height for images displayed in full size.";
			bSettings.AddSetting(OriginalHeight);

			// Layouts
			Hashtable layouts = new Hashtable();
			foreach(string layoutControl in Directory.GetFiles(HttpContext.Current.Server.MapPath(Config.ModulesPath + "/CRMImage/Layout"), "*.ascx"))
			{
				string layoutControlDisplayName = layoutControl.Substring(layoutControl.LastIndexOf("\\") + 1, layoutControl.LastIndexOf(".") - layoutControl.LastIndexOf("\\") - 1);
				string layoutControlName = layoutControl.Substring(layoutControl.LastIndexOf("\\") + 1);
				layouts.Add(layoutControlDisplayName, layoutControlName);
			}

			// Thumbnail Layout Setting
			SettingItemSpecial ThumbnailLayoutSetting	=   new SettingItemSpecial(ImStr.ThumbnailLayout,
                                                                    new CustomListDataType(layouts, "Key", "Value"));
			ThumbnailLayoutSetting.Required		        =   true;
			ThumbnailLayoutSetting.Value		        =   "DefaultThumbnailView.ascx";
			ThumbnailLayoutSetting.Order		        =   80;
            ThumbnailLayoutSetting.ExtendedGroupName    =   extgrp;
            ThumbnailLayoutSetting.ResourceFile         =   ImStr.ResourceFile;
            ThumbnailLayoutSetting.ResourceItem         =   ImStr.ResourceItem;
            ThumbnailLayoutSetting.EnglishName	        =   "Thumbnail Layout";
            ThumbnailLayoutSetting.Description	        =   "Layout for thumbnail images";
			bSettings.AddSetting(ThumbnailLayoutSetting);


			// Image Layout Setting
			SettingItemSpecial ImageLayoutSetting	    =   new SettingItemSpecial(ImStr.ImageLayout,new CustomListDataType(layouts, "Key", "Value"));
			ImageLayoutSetting.Required			        =   true;
			ImageLayoutSetting.Value			        =   "DefaultImageView.ascx";
			ImageLayoutSetting.Order			        =   90;
            ImageLayoutSetting.ExtendedGroupName        =   extgrp;
            ImageLayoutSetting.ResourceFile             =   ImStr.ResourceFile;
            ImageLayoutSetting.ResourceItem             =   ImStr.ResourceItem;
            ImageLayoutSetting.EnglishName		        =   "Full Size Layout";
            ImageLayoutSetting.Description		        =   "Layout for images when in full size mode";
			bSettings.AddSetting(ImageLayoutSetting);

            // These options are also available specially for situation where the portal is used outside CRM to allow
            // easier filling with images from outside also
            // Repeat Direction Options
            ArrayList repeatDirectionOptions	= new ArrayList();
            repeatDirectionOptions.Add(new SettingOption((int)RepeatDirection.Horizontal, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURES_HORIZONTAL", "Horizontal")));
            repeatDirectionOptions.Add(new SettingOption((int)RepeatDirection.Vertical, LocalizeHelper.Localize(ImStr.ResourceFile,ImStr.ResourceItem,"PICTURES_VERTICAL", "Vertical")));

            // Repeat Direction Setting
            SettingItemSpecial RepeatDirectionSetting	=   new SettingItemSpecial(ImStr.RepeatDirection,
                                                                new CustomListDataType(repeatDirectionOptions, "Name", "Val"));
            RepeatDirectionSetting.Required		        =   true;
            RepeatDirectionSetting.Value		        =   ((int)RepeatDirection.Horizontal).ToString();
            RepeatDirectionSetting.Order		        =   100;
            RepeatDirectionSetting.ExtendedGroupName    =   extgrp;
            RepeatDirectionSetting.ResourceFile         =   ImStr.ResourceFile;
            RepeatDirectionSetting.ResourceItem         =   ImStr.ResourceItem;
            RepeatDirectionSetting.EnglishName	        =   "Repeat direction";
            RepeatDirectionSetting.Description	        =   "Direction for images repetition";
			bSettings.AddSetting(RepeatDirectionSetting);

            // Repeat Columns Setting
            SettingItemSpecial RepeatColumns	        =   new SettingItemSpecial(ImStr.RepeatColumns,new IntegerDataType());
            RepeatColumns.Required				        =   true;
            RepeatColumns.Value					        =   "4";
            RepeatColumns.Order					        =   110;
            RepeatColumns.ExtendedGroupName             =   extgrp;
            RepeatColumns.ResourceFile                  =   ImStr.ResourceFile;
            RepeatColumns.ResourceItem                  =   ImStr.ResourceItem;
            RepeatColumns.MinValue				        =   1;
            RepeatColumns.MaxValue				        =   200;
            RepeatColumns.EnglishName			        =   "Columns number";
            RepeatColumns.Description			        =   "How many columns displayed on a same line";
			bSettings.AddSetting(RepeatColumns);

            // PicturesPerPage
            SettingItemSpecial PicturesPerPage	        =   new SettingItemSpecial(ImStr.PicturePerPage,new IntegerDataType());
            PicturesPerPage.Required			        =   true;
            PicturesPerPage.Value				        =   "12";
            PicturesPerPage.Order				        =   120;
            PicturesPerPage.ExtendedGroupName           =   extgrp;
            PicturesPerPage.ResourceFile                =   ImStr.ResourceFile;
            PicturesPerPage.ResourceItem                =   ImStr.ResourceItem;
            PicturesPerPage.MinValue			        =   1;
            PicturesPerPage.MaxValue			        =   999;
            PicturesPerPage.EnglishName			        =   "Images/Page";
            PicturesPerPage.Description			        =   "How many pictures on each page";
			bSettings.AddSetting(PicturesPerPage);


			//If false the input box for bulk loads will be hidden
			SettingItemSpecial AllowBulkLoad	        =   new SettingItemSpecial(ImStr.AllowBulkLoad,new BooleanDataType());
			AllowBulkLoad.Value					        =   "false";
			AllowBulkLoad.Order					        =   130;
            AllowBulkLoad.ExtendedGroupName             =   extgrp;
            AllowBulkLoad.ResourceFile                  =   ImStr.ResourceFile;
            AllowBulkLoad.ResourceItem                  =   ImStr.ResourceItem;
            AllowBulkLoad.EnglishName			        =   "Allow server bulk load";
            AllowBulkLoad.Description			        =   "Checked will allow copying all images from a server folder.";
			bSettings.AddSetting(AllowBulkLoad);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSI InitSettings END.",CrmImageTrace.Sw.Info);
        }
    }

    /// <summary>
	/// Addon Nice CRMImage module
	/// </summary>
    public partial class CRMImage : PortalCrmImageModuleControl
    {

		#region local vars
		
        int imageItemID								=   1;// internal to count items on page
        int rowCount								=   0; // number of records in each page
        
        // used in itemdatabound loop
        string _PreviousImageDBID                   =   string.Empty;
        CRMImageItem PrevCRMImgItem				    =   null;
        DataListItem PrevItem                       =   null;
        
        #endregion local vars
 
		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
                return new Guid(ImStr.CRMImageGuid);
			}
		}

        public override bool DependsFromCustomCrmEntities
        {
            get{ return true;}
        }
        
        /// <summary>
        /// SortedList of entities/version from which this module depends, schema name is the key, version is a string in the form major.minor
        /// </summary>
        public override SortedList<string,string> RelatedCustomEntities
        {
            get
            {
                SortedList<string,string> Lst =   new SortedList<string,string>();
                Lst.Add(ImStr.adnimage,"1.0");
                return Lst;
            }
        }

        #endregion

        #region Properties and Properties overrides

		/// <summary>
		/// Attempt to cache the layout module name
		/// </summary>
		private string _layoutModule	=	string.Empty;
		public string layoutModule
		{
			get
			{
				if (string.IsNullOrEmpty(_layoutModule))
				{
					_layoutModule = Config.ModulesPath + "/CRMImage/Layout/" + Settings[ImStr.ThumbnailLayout].Value;
					if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage layoutModule GET cached: {0}", _layoutModule),CrmImageTrace.Sw.Info);
				}
				return _layoutModule;
			}
		}

		private string _AlbumPath	=	string.Empty;
		public string AlbumPath
		{
			get
			{
				if (string.IsNullOrEmpty(_AlbumPath))
				{
                    if ( Settings[ImStr.CustomAlbumPath].ToBool() )
					    _AlbumPath = Settings[ImStr.AlbumPath].FullPath;
                    else _AlbumPath = portalSettings.CustomSettings[ImStr.AlbumPath].FullPath;
					if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage AlbumPath GET cached: {0}", _AlbumPath),CrmImageTrace.Sw.Info);
				}
				return _AlbumPath;
			}
		}
        

        public string SortKey
        {
            get
            {
                object ob   =   ViewState[ImStr.SortKey];
                if ( ob == null )
                    ob   =   ViewState[ImStr.SortKey]   =   ImStr.DBImageId;
                return (string)ob;
            }
            set
            {
                ViewState[ImStr.SortKey]   =   value;
            }
        }

        public string SortDir
        {
            get
            {
                object ob   =   ViewState["SortDir"];
                if ( ob == null )
                    ob   =   ViewState["SortDir"]   =   "ASC";
                return (string)ob;
            }
            set
            {
                ViewState["SortDir"]   =   value;
            }
        }

        public int CatFilter
        {
            get
            {
                object ob   =   ViewState["CatFilter"];
                if ( ob == null )
                    ob   =   ViewState["CatFilter"]   =   -1;
                return (int)ob;
            }
            set
            {
                ViewState["CatFilter"]   =   value;
            }
        }

        #endregion Properties and Properties overrides

        #region Ctor and Initializer

        /// <summary>
		/// Ctor
		/// Resize Options
		/// NoResize : Do not resize the CRMImage
		/// FixedWidthHeight : Use the width and height specified. 
		/// MaintainAspectWidth : Use the specified height and calculate height using the original aspect ratio
		/// MaintainAspectHeight : Use the specified width and calculate width using the original aspect ration
		/// </summary>
		public CRMImage()
		{
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage Ctor BEG.",CrmImageTrace.Sw.Info);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage Ctor END.",CrmImageTrace.Sw.Info);
		}

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                 =   "CRMIMAGE";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CRMImageSI(bSettings,this);
        }

        #endregion Ctor

        #region Page Load
        
        /// <summary>
		/// The Page_Load event on this page calls the BindData() method
		/// </summary>
		private void Page_Load(object sender, System.EventArgs e)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage Page_Load IsPostBack: {0}, IsInAsyncPostBack: {1}, PageNumber: {2}.",
                    IsPostBack,IsInAsyncPostBack,pgPictures.PageNumber),CrmImageTrace.Sw.Info);

            if (!IsPostBack)
            {
                // If delete ModuleButton is not displayed we must ensure that script is here
                dlPictures.RepeatDirection  =   Settings.ContainsKey(ImStr.RepeatDirection) ? ((RepeatDirection)Int32.Parse(Settings[ImStr.RepeatDirection].Value)) : RepeatDirection.Vertical;
                dlPictures.RepeatColumns    =   Settings.ContainsKey(ImStr.RepeatColumns) ? Int32.Parse(Settings[ImStr.RepeatColumns].Value) : 1;
                pgPictures.RecordsPerPage   =   Settings.ContainsKey(ImStr.PicturePerPage) ? Int32.Parse(Settings[ImStr.PicturePerPage].Value) : 10;
                // Try to collect currents items from query string if we come back from edit or view
                string ob                   =   Request.QueryString[ImStr.CatId]; // beware ImStr.CatId is used in viewstate for filter value
                if ( !string.IsNullOrEmpty(ob))
                    CatFilter               =   int.Parse(ob.ToString());
                ob                          =   Request.QueryString[ImStr.SortKey];
                if ( !string.IsNullOrEmpty(ob))
                    SortKey                 =   ob.ToString();
                ob                          =   Request.QueryString[ImStr.PageNum];
                if ( !string.IsNullOrEmpty(ob))
                    pgPictures.PageNumber   =   int.Parse(ob.ToString());
		        if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage Page_Load CatFilter: {0}, SortKey: {1}, PageNumber: {2}.",CatFilter,SortKey,pgPictures.PageNumber),CrmImageTrace.Sw.Info);
                FillCatCombo();
            }
            BindData(pgPictures.PageNumber);
        }
        
        #endregion Page Load
        
        #region Work methods and handlers

        /// <summary>
        /// Fill the category combobox with values from the CRM image pickList
        /// </summary>
        void FillCatCombo()
        {
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage FillCatCombo BEG.",CrmImageTrace.Sw.Info);
            ArrayList ar                =   GetPickListArray(ImStr.adncategory, ImStr.adnimage);
            CrmListInt itm              =   new CrmListInt("All categories",-1);
            ar.Insert(0,itm);
            RadComboCat.DataSource      =   ar;
            RadComboCat.DataValueField  =   "val";
            RadComboCat.DataTextField   =   "name";
            RadComboCat.DataBind();
            RadComboCat.SelectedValue   =   CatFilter.ToString();
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage FillCatCombo END Count: {0}, CatFilter: {1}.",ar.Count,CatFilter),CrmImageTrace.Sw.Info);
        }


        private void Page_Changed(object sender, System.EventArgs e)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage Page_Changed BEG PageNumber: {0}.", pgPictures.PageNumber),CrmImageTrace.Sw.Info);
            dlPictures.Controls.Clear();
			BindData(pgPictures.PageNumber);
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage Page_Changed END.",CrmImageTrace.Sw.Info);
		}

        void dlPictures_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage dlPictures_ItemCommand BEG CommandName: {0}, CommandArgument: {1}",e.CommandName,e.CommandArgument),CrmImageTrace.Sw.Info);
            if (e.CommandName == "DeleteImage")
            {
                DeleteImage(e.CommandArgument.ToString());
            }
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage dlPictures_ItemCommand END CommandName: {0}, CommandArgument: {1}",e.CommandName,e.CommandArgument),CrmImageTrace.Sw.Info);
        }

        void RadComboDir_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage RadComboDir_SelectedIndexChanged Value: {0}",e.Value),CrmImageTrace.Sw.Info);
            SortDir     =   e.Value;
            BindData(pgPictures.PageNumber);
        }

        void RadComboSort_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage RadComboSort_SelectedIndexChanged Value: {0}",e.Value),CrmImageTrace.Sw.Info);
            SortKey     =       e.Value;
            BindData(pgPictures.PageNumber);
        }

        void RadComboCat_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage RadComboCat_SelectedIndexChanged Value: {0}",e.Value),CrmImageTrace.Sw.Info);
            CatFilter               =   int.Parse(e.Value);
            // we must restart at first page
            pgPictures.PageNumber   =   1;
            BindData(pgPictures.PageNumber);
        }

        void dlPictures_ItemCreated(object sender, DataListItemEventArgs e)
        {
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage dlPictures_ItemCreated BEG IsUnderCRM: {0}, IsInAsyncPostBack: {1}, ItemIndex: {2}, Item.ItemType: {3}, Item.ID: {4}, Item.HasControls: {5}.", 
                    new object[]{IsUnderCRM,IsInAsyncPostBack,e.Item.ItemIndex,e.Item.ItemType,e.Item.ID,e.Item.HasControls()}),CrmImageTrace.Sw.Info);
            e.Item.ID   =   string.Format("Itm_{0}",e.Item.ItemIndex);
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage dlPictures_ItemCreated END Item.ID: {0}.", e.Item.ID),CrmImageTrace.Sw.Info);
        }

        /// <summary>
        /// Add a ToolTip to the loaded image
        /// Add the confirm script
        /// </summary>
        void AddToolTipImage(CRMImageItem ImgItem)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage AddToolTipImage BEG ImgItem.ID: {0}, ClientID: {1}.",ImgItem.ID,ImgItem.ClientID),CrmImageTrace.Sw.Info);
            Image img           =   (Image)ImgItem.FindControl("CrmImg");
            if (!Object.Equals(img, null))
            {
                string val      =   ImgItem.imageModifiedSrc;
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage AddToolTipImage img.ClientID: {0}, url: {1}.",img.ClientID,val),CrmImageTrace.Sw.Info);
                RadToolTipManager1.TargetControls.Add(img.ClientID, val, true);
            }
            // Add confirm delete
            ImageButton BtnDelImage =   (ImageButton)ImgItem.FindControl("BtnDelImage");

            if (!Object.Equals(BtnDelImage, null) )
            {
                string msg                  =   LocalizeHelper.Localize("CONFIRM_DELETE", "Confirm Delete");
                string title                =   LocalizeHelper.Localize("DELETE", "Delete");
                ADNPage.setClientConfirmAttributes(BtnDelImage,msg,title);
                // Tooltipyfy for text this button
                //((ADNPage)Page).AddToolTipTarget(BtnDelImage.ClientID,true);
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",BtnDelImage.ID);
                tt.IsClientID           =   true;
                tt.TargetControlID      =   BtnDelImage.ClientID;
                tt.Position             =   ToolTipPosition.BottomRight;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                BtnDelImage.Parent.Controls.AddAt(BtnDelImage.Parent.Controls.IndexOf(BtnDelImage),tt);
                tt.Text                 =   string.Format("Delete {0}",ImgItem.imageCaption);
                ((ADNPage)Page).AddAjaxSetting(BtnDelImage, ((ADNPage)Page).LoadedModules[ModuleID]);
                if ( RadToolTipManager1 != null )
                    ((ADNPage)Page).AddAjaxSetting(BtnDelImage, RadToolTipManager1);
            }
            // If tootip manager in Page tooltipyfy all available
            // Any edit button/image/else
            Control Ctl                 =   ImgItem.FindControl("ImgEdit");
            if (!Object.Equals(Ctl, null))
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.BottomRight;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   string.Format("Edit {0}",ImgItem.imageCaption);
            }
            // Caption
            Ctl                         =   ImgItem.FindControl("imgCaption");
            if (!Object.Equals(Ctl, null) && (ImgItem.imageShortDescription != string.Empty) )
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   ImgItem.imageShortDescription;
            }
            // Category
            Ctl                         =   ImgItem.FindControl("imgCategory");
            if (!Object.Equals(Ctl, null))
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                string strCat           =   ImgItem.imageCategory;
                foreach (RadComboBoxItem it in RadComboCat.Items)
                {
                    if ( it.Value == strCat)
                    {
                        tt.Text         =   it.Text;
                        break;
                    }
                }
            }
            // ShortDescription
            Ctl                         =   ImgItem.FindControl("imgShortDescription");
            if (!Object.Equals(Ctl, null)  && (ImgItem.imageShortDescription != string.Empty) )
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   ImgItem.imageShortDescription;
            }
            //LongDescription
            Ctl                         =   ImgItem.FindControl("imgLongDescription");
            if (!Object.Equals(Ctl, null) && (ImgItem.imageLongDescription != string.Empty) )
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   ImgItem.imageLongDescription;
            }
        }
        
        
        /// <summary>
        /// This method fills a datalistItem with data from db concerning one image
        /// To format values, it loads a template (an ascx control which inherits from CrmImageItem object)
        /// It fills the metadata propert of CrmImageItem from metadat readen from DB, then it adds usefull data concerning actual image display 
        /// allowing to display image, format edit and view urls, etc.
        /// Checks the metadata format version to allow evolutions
        /// </summary>
		private void CRMImage_ItemDataBound(object sender, DataListItemEventArgs e)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage CRMImage_ItemDataBound BEG IsUnderCRM: {0}, IsInAsyncPostBack: {1}, ItemIndex: {2}, Item.ItemType: {3}, Item.ID: {4}, Item.HasControls: {5}.", 
                    new object[]{IsUnderCRM,IsInAsyncPostBack,e.Item.ItemIndex,e.Item.ItemType,e.Item.ID,e.Item.HasControls()}),CrmImageTrace.Sw.Info);
			try
			{
				if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage CRMImage_ItemDataBound LoadControl: {0}.", layoutModule),CrmImageTrace.Sw.Info);
				CRMImageItem CRMImgItem				=   (CRMImageItem)Page.LoadControl(layoutModule);
				System.Data.Common.DbDataRecord di	=   (System.Data.Common.DbDataRecord)e.Item.DataItem;
                
                CRMImgItem.BindFromDB(di,AlbumPath,
                    imageItemID++,
                    IsEditable,
                    IsDeletable,
                    RequestEntityTypename,
                    EntityName,
                    ModuleID,
                    e.Item.ItemIndex,
                    pgPictures.PageNumber,
                    CatFilter,
                    SortKey);

                // when not displaying the crm adn_image entity in crm we get row count from db
                if (rowCount == 0)
                    rowCount                        =   (int)di["RecordCount"];

				XmlElement PreviousImageId		    =   null;
                if (_PreviousImageDBID != string.Empty )
				    PreviousImageId				    =   CRMImgItem.AddMetadataElement("PreviousImageDBID",_PreviousImageDBID);
				_PreviousImageDBID                  =   di[ImStr.DBImageId].ToString();

                // We don't directly add CRMImgItem to DataListItem, because we want to insert in metadata the next image db Id,
                // so we wait for next loop to insert it and add CRMImgItem to the DatalistItem controls collection
                if ( PrevCRMImgItem != null )
                {
                    // store this imageid in the previous datalistitem to allow prev/next
				    XmlElement NextImageId	        =   PrevCRMImgItem.AddMetadataElement("NextImageDBID",_PreviousImageDBID);
                    PrevItem.Controls.Add(PrevCRMImgItem);
                    PrevCRMImgItem.DataBind();
			        if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage CRMImage_ItemDataBound PrevCRMImgItem added to PrevItem.ID: {0}.",PrevItem.ID),CrmImageTrace.Sw.Info);
                    AddToolTipImage(PrevCRMImgItem);
                }
                PrevCRMImgItem                      =   CRMImgItem;
                PrevItem                            =   e.Item;
			}
			catch (Exception ex)
			{
				if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImage CRMImage_ItemDataBound ex : {0}.", ex),CrmImageTrace.Sw.Info);
                throw;
			}
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImage CRMImage_ItemDataBound END.",CrmImageTrace.Sw.Info);
		}

		/// <summary>
        /// The Binddata method on this User Control is used to
		/// obtain a DataReader of CRMImage information from the CRMImage
		/// table, and then databind the results to a templated DataList
		/// server control. It uses the AddonNice.CRMImageDB()
		/// data component to encapsulate all data functionality.
        /// If we are under CRM, we limit our action to display the EntityID asked by CRM or a default entityID for creation mode
        /// if not under CRM we display with paging all the existing images
		/// </summary>
		private void BindData(int page)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage BindData BEG Page: {0}, RecordsPerPage: {1}, IsInAsyncPostBack: {2}, IsUnderCRM: {3}.", 
                    new object[]{page,pgPictures.RecordsPerPage, IsInAsyncPostBack,IsUnderCRM}),CrmImageTrace.Sw.Info);

            SqlDataReader dsCRMImage	        =   null;
            imageItemID					        =   1 + (pgPictures.RecordsPerPage*(page-1));
            //initialize image counter
            rowCount					        =   0;
            // get imageLib Id from settings
            int imageLibId                      =   Settings[ImStr.ImageLibId].ToInt();
            try
            {
                dsCRMImage			            =   new CRMImageDB().GetAllCRMImagesPagedEx(imageLibId,page,pgPictures.RecordsPerPage,CatFilter,SortKey+" "+SortOrder); // all the image out of CRM
                if ( dsCRMImage != null )
                {
                    _PreviousImageDBID          =   string.Empty;
                    PrevCRMImgItem              =   null;
                    PrevItem                    =   null;
                    RadToolTipManager1.TargetControls.Clear();
                    dlPictures.DataSource       =   dsCRMImage;
                    dlPictures.DataKeyField     =   ImStr.DBImageId;
                    dlPictures.DataBind();
                    // We bind last element due to prev/next image management
                    if ( PrevCRMImgItem != null)
                    {
                        PrevItem.Controls.Add(PrevCRMImgItem);
                        PrevCRMImgItem.DataBind();
		                if ( CrmImageTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage BindData PrevCRMImgItem added to PrevItem.ID: {0}.",PrevItem.ID),CrmImageTrace.Sw.Info);
                        AddToolTipImage(PrevCRMImgItem);
                        }
                    pgPictures.RecordCount	=   rowCount;
	                if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage BindData RecordCount: {0}.",rowCount),CrmImageTrace.Sw.Info);
                }
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImage BindData ex: {0}", ex),CrmImageTrace.Sw.Info);
                throw;
            }
            finally
            {
                if (dsCRMImage != null)
                    dsCRMImage.Close();
            }
    		if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage BindData END rowCount: {0}.",rowCount),CrmImageTrace.Sw.Info);
		}

        /// <summary>
		/// Delete a CRMImage.  It  uses the AddonNice.CRMImageDB()
		/// data component to encapsulate all data functionality.
		/// </summary>
        void DeleteImage(string arg)
		{
            // Only attempt to delete the item if it is an existing item
			// (new items will have ImStr.ItemCrmID of Guid.Empty)
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage DeleteImage args: {0}, IsDeletable: {1}", arg,IsDeletable),CrmImageTrace.Sw.Info);
            if ( !IsDeletable )
                return;
            CRMImageDB ImageDB          =   new CRMImageDB();
            int ImageDBID               =   int.Parse(arg);
			
            string PathToDelete			=   Server.MapPath(AlbumPath) + "\\";

			SqlDataReader dr			=   null;
			string filename				=   string.Empty;
			string thumbnailFilename	=   string.Empty;
            Guid CrmImageId             =   Guid.Empty;
			try
			{
                dr						=   ImageDB.GetCRMImage(ImageDBID);
				// Read first row from database
				if (dr.Read())
				{
				    CrmImageId  	    =   (Guid)dr[ImStr.DBCrmImageId];
				    XmlDocument metadata	= new XmlDocument();
					metadata.LoadXml((string)dr[ImStr.DBMetadataXml]);
					filename			=   GetMetadata(metadata,ImStr.ModifiedFilename);
					thumbnailFilename	=   GetMetadata(metadata,ImStr.ThumbnailFilename);
				}
			}
			catch(Exception ex)
			{
				if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImage DeleteImage ex :{0}",ex),CrmImageTrace.Sw.Info);
                throw;
			}
			finally
			{
				if  ( dr != null )
					dr.Close();
			}


            //Delete the record from database.
            try
            {
                ImageDB.DeleteCRMImage(ImageDBID);
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImage DeleteImage ex :{0}", ex),CrmImageTrace.Sw.Info);
                throw;
            }

            //Delete the object from CRM.
            if ( CrmImageId != Guid.Empty ) // don't delete the entity when under CRM (?)
            {
                try
                {
                    ADNDynImage im       =   new ADNDynImage(PortalSecurity.Wrapper,CrmImageId);
                    im.Delete();
                }
                catch (Exception ex)
                {
                    if ( CrmImageTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImage DeleteImage Delete ADNDynImage ex :{0}", ex),CrmImageTrace.Sw.Info);
                    //throw; // we could always delete the object from CRM if it fails here
                }
            }
			//Delete the files
			try
			{
				File.Delete(PathToDelete + filename);
				File.Delete(PathToDelete + thumbnailFilename);
			}
			catch(Exception ex1)
			{
				// We don't really have much to do at this point
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImage DeleteImage Error deleting physical files ex :{0}", ex1),CrmImageTrace.Sw.Info);
			}
            // We must rebind 
            // and check if current page still exists
            int oldPgNumber =   pgPictures.PageNumber;
            pgPictures.RecordCount--;
            if (pgPictures.PageCount <= oldPgNumber)
            {
                pgPictures.PageNumber--;
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage DeleteImage oldPgNumber: {0}, PageNumber: {1}",oldPgNumber,pgPictures.PageNumber),CrmImageTrace.Sw.Info);
            }
            BindData(pgPictures.PageNumber);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImage DeleteImage END",CrmImageTrace.Sw.Info);
		}
        
        void GridDock_Command(object sender, DockCommandEventArgs e)
        {
            if (CrmImageTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage GridDock_Command BEG name: {0}.", e.Command.Name),CrmImageTrace.Sw.Info);
            DataListItem nd  = dlPictures.SelectedItem;
            if ( nd == null )
                return;
            switch (e.Command.Name)
            {
                default:
                   break;
            }
        }

        #endregion Work methods and handlers

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage Page_PreInit BEG.",CrmImageTrace.Sw.Info);
            AddText     =   "ADD"; //"Add New CRMImage"
            AddUrl      =   Config.ModulesPath + "/CRMImage/CRMImageEdit.aspx";
			base.Page_PreInit(sender, e);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage Page_PreInit END.",CrmImageTrace.Sw.Info);
        }
        
        override protected void OnInit(EventArgs e)
		{
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage OnInit BEG.",CrmImageTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImage OnInit END.",CrmImageTrace.Sw.Info);
		}

		private void InitializeComponent()
		{
            try
            {
                dlPictures.ItemCreated              +=  new DataListItemEventHandler(dlPictures_ItemCreated);
                dlPictures.ItemDataBound            +=  new DataListItemEventHandler(CRMImage_ItemDataBound);
                dlPictures.ItemCommand              +=  new DataListCommandEventHandler(dlPictures_ItemCommand);
                pgPictures.OnMove                   +=  new EventHandler(Page_Changed);
                Load                                +=  new EventHandler(Page_Load);

                RadComboDir.SelectedIndexChanged    +=  new RadComboBoxSelectedIndexChangedEventHandler(RadComboDir_SelectedIndexChanged);
                RadComboSort.SelectedIndexChanged   +=  new RadComboBoxSelectedIndexChangedEventHandler(RadComboSort_SelectedIndexChanged);
                RadComboCat.SelectedIndexChanged    +=  new RadComboBoxSelectedIndexChangedEventHandler(RadComboCat_SelectedIndexChanged);
                GridDock.Command                +=  new DockCommandEventHandler(GridDock_Command);
                RadDockLayout1.LoadDockLayout   +=  new DockLayoutEventHandler(DockWindowLayout_LoadDockLayout);
                RadDockLayout1.SaveDockLayout   +=  new DockLayoutEventHandler(DockWindowLayout_SaveDockLayout);
            }
            catch(Exception ex)
            { 
                if (CrmImageTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImage InitializeComponent ex: {0}.",ex), CrmImageTrace.Sw.Info);
                throw;
            }
		}

		#endregion
	}
}
